package net.rlair.sbdemo.controller;

import net.rlair.sbdemo.dao.jdbctemplate.GuanBoDao;
import net.rlair.sbdemo.dao.jpa.YangbairongJpaUserRepository;
import net.rlair.sbdemo.dao.mybatis.bootmapper.YangbairongMyBatisUserDao;
import net.rlair.sbdemo.entity.User;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import net.rlair.sbdemo.service.IsolationLevelMainYaoyi;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @author lixudong
 */
@Controller
@RequestMapping("user")
public class UserController {

    @Resource
    private YangbairongJpaUserRepository yangbairongJpaUserRepository;
    @Resource
    private IsolationLevelMainYaoyi isolationLevelMainYaoyi;
    @Resource
    private YangbairongMyBatisUserDao myBatisUserDao;
    @Resource
    private GuanBoDao guanBoDao;

    @GetMapping("/jpaFindUsersByPage")
    @ResponseBody
    public Object findUsersByPage(@RequestParam(value = "page", defaultValue = "0") final int page,
            @RequestParam(value = "pageSize", defaultValue = "15") final int pageSize) {
        return yangbairongJpaUserRepository.findAll(PageRequest.of(page, pageSize));
    }

    @RequestMapping("/mybatisFindUsersByPage")
    @ResponseBody
    public Object mybatisFindUsersByPage(@RequestParam(value = "page", defaultValue = "0") final int page,
            @RequestParam(value = "pageSize", defaultValue = "15") final int pageSize) {
        final Pageable pageable = PageRequest.of(page, pageSize);
        return new PageImpl<>(myBatisUserDao.findUsersByPage(pageable), pageable, myBatisUserDao.countUser());
    }

    @RequestMapping("save")
    @ResponseBody
    public Object save(final User user) {
        user.setCreated(new Date());
        user.setUpdated(new Date());
        yangbairongJpaUserRepository.save(user);
        myBatisUserDao.insertUser(user);
        return "2132131";
    }

    @GetMapping("findAllUsersGuanBo")
    @ResponseBody
    public Object findAllUsersGuanBo(@RequestParam(value = "page", defaultValue = "0") final int pageNo,
            @RequestParam(value = "pageSize", defaultValue = "10") final int pageSize) {
        return guanBoDao.findAllUser(pageNo, pageSize);
    }

    @GetMapping("/dirtyRead")
    @ResponseBody
    public Object dirtyRead() {
        isolationLevelMainYaoyi.dirtyRead();
        return "success";
    }

}
